'''
filename: check
author: yinwenlu
datetime: 2019/11/5 17:58
software: PyCharm
'''
import datetime

import threadpool

from Redis.redis import RedisConnect
from cron.job import isInFixedTimeFixedPrice
from cron.job_func import getSpider
from web.service.api_service.public.MyThread import MyThread
from web.service.overData.sql_db import getMtShops, getEleShops, getMOrEBsaeInfo, formatAdtAndSpt, checkAndcorrectTime, \
    checkAndCorrectBiddingStatus, checkAndCorrectPlans, checkBidding, getMOrEBsaeInfoCheck
from web.service.public.result import resultJson


def serviceApiCheck():
    '''对checkShopBug接口提供服务'''
    '''1、获取所有未删除的店铺信息'''
    mtShops=getMtShops()
    eleShops=getEleShops()
    shops=mtShops+eleShops
    redis = RedisConnect()
    redis_result = redis.get("checkBug" + datetime.datetime.now().strftime("%Y-%m-%d %H"))
    if redis_result:
        rds_result = eval(str(redis_result, encoding='utf-8'))
        if len(rds_result) < len(shops):
            pass
        else:
            return {"date": rds_result, "code": 6000, "message": "成功"}
    result=[]
    #p = multiprocessing.Pool(10)
    threadList = []
    results = []
    data = []
    for i in range(0,len(shops)):
        data.append(dict(shop = shops[i]))
    def get_result(request, result):
        results.append(result)
    pool = threadpool.ThreadPool(30)
    requests = threadpool.makeRequests(checkShops, data, get_result)
    # 将每一个线程请求扔进线程池
    [pool.putRequest(req) for req in requests]
    # 等待data被消耗完，所有线程运行结束。
    pool.wait()
#   print(results)

    # threadLenth = len(shops)
    # for i in range(0,threadLenth):
    #     #if shops[i].account=='wmOLDy38746':
    #
    #     date = dict(shop=shops[i])
    #     # result.append(p.map(checkShops,(date,))[0])
    #     t = MyThread(checkShops, args=(date,))
    #     threadList.append(t)
    #     t.start()
    # for t in threadList:
    #     t.join()  # 一定要join，不然主线程比子线程跑的快，会拿不到结果
    #     result.append(t.get_result())
    # i = 0
    # for rs in result:
    #     if len(rs.get("message"))>5:
    #         i=i+1
    redis = RedisConnect()
    redis.rc.set("checkBug"+datetime.datetime.now().strftime("%Y-%m-%d %H"), str(results), ex=60*60)
    return {"date":results,"code":6000,"message":"成功"}


def checkShops(date):
    '''
    多进程执行该检查诊断店铺的程序
    :param date:
    :return:
    '''

    shop=date.get("shop")
    shopType=shop.shopType
    cookies=shop.cookies
    adTime=shop.adTime
    shipTime=shop.shipTime
    shopid=shop.mtId if shopType==1 else shop.eleId
    shopName = shop.mtName if shopType == 1 else shop.eleName
    #spider=getSpider(cookies,shopType, shop.ip)
    guard = shop.guard
    lock = shop.isremake
    historyCurbid = shop.historyCurbid
    isInFixedTime = 0
    status = 0
    if historyCurbid:
        try:
            historyCurbid = eval(historyCurbid)
        except:
            historyCurbid = historyCurbid
        isInFixedTime = isInFixedTimeFixedPrice(historyCurbid.get("curbid",None)).get("inFixedTime",None)
        status = historyCurbid.get("status", 0)
    #获取营业时间和推广状态
    try:
        if shop.shopType == 1:
            ip = shop.ip
            ip = {'https':'https://ldy:ldy@123.@'+ip, 'http':'http://ldy:ldy@123.@'+ip}
        else:
            ip = None
        result, spider = getMOrEBsaeInfoCheck(shopType,cookies,ip)
        if result.get("error")==1:
            message=[]
            shopName = shop.mtName if shopType == 1 else shop.eleName
            message.append(result.get("message", ""))
            message+=['','','','']
            checkAllResult = {"shopName": shopName, "message": message}
            return resultJson(checkAllResult, 6000, "程序正常返回数据", 1)
        newShipTime=result.get("date",{}).get("shipTime",'')
        shopStatus=result.get("date",{}).get("shopStatus",'')
        isEnable=shop.isenable
        '''判断推广时间是否与营业时间相符合
        1、获取正确格式的营业时间和推广时间
        2、和数据库时间相比，不正确的时间进行更新
        2、不符合，将正确的推广时间进行更新到数据库，并且重新做计划,返回处理后的推广时间'''
        #1、获取正确格式的推广时间和营业时间，更新系统的竞价状态未1
        formatTimeResult=formatAdtAndSpt(newShipTime)

        adTimeList=formatTimeResult.get("date",{}).get("adTimeResult",[])
        shipTimeList = formatTimeResult.get("date", {}).get("shipTimeResult", [])
        adTimeList=str(adTimeList)

        #与数据库时间进行比较，不正确的进行更新,
        checkTimeResult=checkAndcorrectTime(shopid,shopType,adTime,shipTime,adTimeList,shipTimeList)

        #检查并纠正未删除所有店铺的推广状态
        ct=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        cDay = datetime.datetime.now().strftime("%Y-%m-%d")
        checkTuiGResult = {"message":"锁定状态或监控或者定时定价不修改推广状态"}
        if guard == 0 or (status and not isInFixedTime):
            if lock == 0:
                checkTuiGResult = checkAndCorrectBiddingStatus(adTimeList, spider, shopStatus, ct, cDay, shopType)

        #检查计划是否生成完整
        checkPlansResult=checkAndCorrectPlans(shopid,shopType,cDay)

        #检查日志是否生成
        #checkBiddingResult=checkBidding(shopid,shopType,cDay,ct,adTimeList)


        message=[]
        message.append(formatTimeResult.get("message",""))
        message.append(checkTimeResult.get("message", ""))
        message.append(checkTuiGResult.get("message", ""))
        message.append(checkPlansResult.get("message", ""))
        message.append("")
        # message.append(checkPlansResult.get("message", ""))
        # message.append(checkBiddingResult.get("message", ""))
        error=formatTimeResult.get("error") or checkTimeResult.get("error") or \
              checkTuiGResult.get("error",0) or checkPlansResult.get("error",0)#or checkPlansResult.get("error") or checkBiddingResult.get("error")
        checkAllResult={"shopName":shopName,"message":message}
        return resultJson(checkAllResult,6000,"程序正常返回数据",error)
    except:
        return resultJson({"shopName":shopName,"message":["数据错误","数据错误","数据错误","数据错误","数据错误"]}, 6001, "数据错误",1)


